package org.swingfly.works.jutils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.Random;

public class ReflectUtils {
//    public static <T> T getProxyInstance(final Object o,Class<T> interfaceClass){
//        Object proxy = Proxy.newProxyInstance(ReflectUtils.class.getClassLoader(),interfaceClass,new InvocationHandler() {
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                return method.invoke(o,args);
//            }
//        });
//       return proxy;
//    }

    public static void main(String[] args) throws Exception {
        Interface clazz = Clazz.create();
        long begin = System.currentTimeMillis();
        for(int i=0;i<1000;i++){
            clazz.a();
//            clazz.b();
        }
        long end = System.currentTimeMillis();
        System.out.println("reflect:"+(end-begin));
        clazz = Clazz.clazz;
        begin = System.currentTimeMillis();
        for(int i=0;i<1000;i++){
            clazz.a();
//            clazz.b();
        }
        end = System.currentTimeMillis();
        System.out.println("class:"+(end-begin));
    }

    public static interface Interface {
        public void a() throws InterruptedException;

        public int b();
    }

    public static class Clazz implements Interface {

        private static Clazz clazz = new Clazz();

        public void a() throws InterruptedException {
//            System.out.println("method a in Clazz");
            Thread.sleep(15);
        }

        public int b() {
            return (int) (Math.random() * 100);
        }



        public static Interface create() {
            Interface anInterface = (Interface) Proxy.newProxyInstance(ReflectUtils.class.getClassLoader(), new Class[]{Interface.class}, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                    System.out.println("before invoke: proxy");
                    Object result = method.invoke(clazz, args);
//                    System.out.println("after invoke: proxy");
                    return result;
                }
            });
            return anInterface;
        }
    }
}
